package com.demo.aop;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.context.annotation.Scope;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author : YU.TAN
 * @date : 2021/10/26 14:11
 * order越小越是最先执行，但更重要的是最先执行的最后结束。order默认值是2147483647
 */
@Component
@Scope
@Aspect
@Order(1)
public class LockAspect {

    /**
     * 默认为非公平锁，true为公平锁
     */
    private Lock lock = new ReentrantLock(true);

    @Pointcut("@annotation(com.demo.aop.Servicelock)")
    public void lockAspect() {

    }

    @Around("lockAspect()")
    public Object around(ProceedingJoinPoint joinPoint) {
        lock.lock();
        Object o = null;
        try {
            o = joinPoint.proceed();

        } catch (Throwable throwable) {
            throwable.printStackTrace();
        } finally {
            lock.unlock();
        }
        return o;
    }

}
